package NC;

public class NC3 {
}

// 判断一个链表有没有环 ，有的话返回链表的头

class Solution3 {
    public ListNode detectCycle(ListNode head) {
        if (head==null) return null;
        ListNode slow = head;
        ListNode fast = head;
        boolean flag =false;
        while (fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                ListNode node1 = head;
                ListNode node2 = fast;
                while(node1 != node2){
                    node1 = node1.next;
                    node2 = node2.next;
                }
                return node1;
            }
        }
        return null;
    }
}